package com.zhb.lkd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhb.lkd.base.PageResponse;
import com.zhb.lkd.exception.BusinessException;
import com.zhb.lkd.mapper.NodeMapper;
import com.zhb.lkd.pojos.entity.Node;
import com.zhb.lkd.pojos.entity.Partner;
import com.zhb.lkd.pojos.entity.Region;
import com.zhb.lkd.mapper.RegionMapper;
import com.zhb.lkd.pojos.entity.VendingMachine;
import com.zhb.lkd.pojos.vo.PartnerVo;
import com.zhb.lkd.pojos.vo.RegionVo;
import com.zhb.lkd.service.IRegionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 运营区域 服务实现类
 * </p>
 *
 * @author haibin
 * @since 2024-08-18
 */
@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements IRegionService {
   @Resource
    private NodeMapper nodeMapper;
    /**
     * 区域搜索
     * @param pageIndex
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public PageResponse search(Integer pageIndex, Integer pageSize, String name) {
        //1.检查参数
        //2.分页查询
        Page<Region> page = lambdaQuery()
                .like(StrUtil.isNotBlank(name), Region::getRegionName, name)
                .page(new Page<>(pageIndex, pageSize));
        List<RegionVo> partnerVos = page.getRecords().stream().map(region -> {
            RegionVo regionVo = BeanUtil.copyProperties(region, RegionVo.class);
            //查询数量
            Long count = nodeMapper.selectCount(Wrappers.<Node>lambdaQuery().eq(Node::getRegionId, region.getId()));
            if (count!=null||count!=0){
                regionVo.setNodeCount(Math.toIntExact(count));
            }else {
                regionVo.setNodeCount(0);
            }
            regionVo.setName(region.getRegionName());
            return regionVo;
        }).collect(Collectors.toList());
        return new PageResponse(page,partnerVos);
    }

    /**
     * 新增区域
     * @param region
     */
    @Override
    public void create(Region region) {
        //1.检查参数
        if (StrUtil.isBlank(region.getRegionName())){
            throw new BusinessException(500,"区域名称不能为空");
        }
        //2.保存
        save(region);
    }
}
